import { useQuery } from '@tanstack/react-query';
import { tasksApi, dataApi, healthApi } from '../services/api';
import {
  ChartBarIcon,
  DocumentTextIcon,
  ServerIcon,
  ClockIcon,
} from '@heroicons/react/24/outline';

export default function DashboardPage() {
  // 获取任务统计
  const { data: taskStats } = useQuery({
    queryKey: ['taskStats'],
    queryFn: () => tasksApi.getTaskStats(),
    refetchInterval: 30000, // 30秒刷新一次
  });

  // 获取数据统计
  const { data: dataStats } = useQuery({
    queryKey: ['dataStats'],
    queryFn: () => dataApi.getDataStats(),
    refetchInterval: 30000,
  });

  // 获取系统健康状态
  const { data: healthStatus } = useQuery({
    queryKey: ['health'],
    queryFn: () => healthApi.getHealth(),
    refetchInterval: 10000, // 10秒刷新一次
  });

  const stats = [
    {
      name: '总任务数',
      value: taskStats?.data?.total || 0,
      icon: DocumentTextIcon,
      color: 'text-blue-600',
      bgColor: 'bg-blue-50',
    },
    {
      name: '运行中任务',
      value: taskStats?.data?.running || 0,
      icon: ClockIcon,
      color: 'text-yellow-600',
      bgColor: 'bg-yellow-50',
    },
    {
      name: '已完成任务',
      value: taskStats?.data?.completed || 0,
      icon: ChartBarIcon,
      color: 'text-green-600',
      bgColor: 'bg-green-50',
    },
    {
      name: '系统状态',
      value: healthStatus?.status === 'healthy' ? '正常' : '异常',
      icon: ServerIcon,
      color: healthStatus?.status === 'healthy' ? 'text-green-600' : 'text-red-600',
      bgColor: healthStatus?.status === 'healthy' ? 'bg-green-50' : 'bg-red-50',
    },
  ];

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">仪表板</h1>
        <p className="mt-1 text-sm text-gray-600">
          系统概览和关键指标监控
        </p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
        {stats.map((stat) => (
          <div
            key={stat.name}
            className="relative overflow-hidden rounded-lg bg-white px-4 py-5 shadow-soft sm:px-6 sm:py-6"
          >
            <div className="flex items-center">
              <div className={`rounded-md p-3 ${stat.bgColor}`}>
                <stat.icon
                  className={`h-6 w-6 ${stat.color}`}
                  aria-hidden="true"
                />
              </div>
              <div className="ml-5 w-0 flex-1">
                <dl>
                  <dt className="truncate text-sm font-medium text-gray-500">
                    {stat.name}
                  </dt>
                  <dd className="text-lg font-semibold text-gray-900">
                    {stat.value}
                  </dd>
                </dl>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* 详细统计 */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        {/* 任务状态分布 */}
        <div className="rounded-lg bg-white p-6 shadow-soft">
          <h3 className="text-lg font-medium text-gray-900 mb-4">
            任务状态分布
          </h3>
          {taskStats?.data?.byStatus && (
            <div className="space-y-3">
              {Object.entries(taskStats.data.byStatus).map(([status, count]) => (
                <div key={status} className="flex items-center justify-between">
                  <span className="text-sm text-gray-600 capitalize">
                    {getStatusLabel(status)}
                  </span>
                  <span className="text-sm font-medium text-gray-900">
                    {count as number}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 引擎使用情况 */}
        <div className="rounded-lg bg-white p-6 shadow-soft">
          <h3 className="text-lg font-medium text-gray-900 mb-4">
            引擎使用情况
          </h3>
          {taskStats?.data?.byEngine && (
            <div className="space-y-3">
              {Object.entries(taskStats.data.byEngine).map(([engine, count]) => (
                <div key={engine} className="flex items-center justify-between">
                  <span className="text-sm text-gray-600 capitalize">
                    {engine}
                  </span>
                  <span className="text-sm font-medium text-gray-900">
                    {count as number}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* 数据统计 */}
      {dataStats?.data && (
        <div className="rounded-lg bg-white p-6 shadow-soft">
          <h3 className="text-lg font-medium text-gray-900 mb-4">
            数据统计
          </h3>
          <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
            <div className="text-center">
              <div className="text-2xl font-bold text-gray-900">
                {dataStats.data.total}
              </div>
              <div className="text-sm text-gray-600">总数据量</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-green-600">
                {dataStats.data.valid}
              </div>
              <div className="text-sm text-gray-600">有效数据</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-blue-600">
                {dataStats.data.processed}
              </div>
              <div className="text-sm text-gray-600">已处理</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-red-600">
                {dataStats.data.invalid}
              </div>
              <div className="text-sm text-gray-600">无效数据</div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function getStatusLabel(status: string): string {
  const labels: Record<string, string> = {
    pending: '待执行',
    running: '运行中',
    completed: '已完成',
    failed: '失败',
    paused: '暂停',
    cancelled: '已取消',
  };
  return labels[status] || status;
}
